import { Component } from "@angular/core";
import { Error } from "./entity/Error";
import { FileService } from "./service/file.service";
import { TextService } from "./service/text.service";
import { SafenlService } from "./service/safenl.service";
import { RecordTimeService } from "./record-time.service";
import { FileUploader } from "ng2-file-upload";
import { Title } from "@angular/platform-browser";
import * as $ from 'jquery';

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "PF2-web1";
  errors: Error[];
  res: boolean;
  strategyList: string[];
  projects: string[];
  versions: string[];

  ccsls: string[];
  owlVersions: string[];
  owl: string;

  pOwls: string[];
  pOwlVersions: string[];
  pOwl: string;

  projectName: string;
  version: string;
  stateFileName: string;
  interval;

  isNew: boolean = true;
  SMTCheck: boolean = false;

  excludeList: string[] = [];
  exclude: string;
  isCCSL: boolean = false;

  getErrors(errors: Error[]) {
    this.res = false;
    this.errors = errors;
    if (
      this.errors[0].errorList.length > 0 ||
      this.errors[1].errorList.length > 0 ||
      this.errors[2].errorList.length > 0
    ) {
      ////console.log(this.errors);
      var popBox = document.getElementById("popBox");
      var popLayer = document.getElementById("popLayer");
      popBox.style.display = "block";
      popLayer.style.display = "block";
    } else {
      ////console.log(errors)
    }
  }

  getProjects(projects: string[]) {
    this.projects = projects;
    if (projects.length == 0) {
      alert("There is no project! You need import a new project!");
    } else {
      var popLayer = document.getElementById("popLayer");
      popLayer.style.display = "block";
      var popBox = document.getElementById("OpenProject");
      popBox.style.display = "block";
    }
  }

  ToCCSL(tag: boolean) {
    var safenl = this.textService.getText();
    var next = confirm('Save change in SafeNL?');
    console.log(next);
    var res = true
    var userName = ''
		if(document.cookie != ''){
			console.log(document.cookie)
			userName = jQuery.parseJSON(document.cookie)['username']
		}
		if(next){
      this.fileService.saveSafeNL(userName, this.projectName, this.fileService.version, safenl).subscribe(version => {
        if(version){
          this.res = true
          alert("save succeed!");
          this.fileService.version = version[0];
          console.log(this.fileService.version)
        }else{
          alert("save failed!");
          return
        }
      });
    }
    if (tag && res){
      var popLayer = document.getElementById("popLayer");
      popLayer.style.display = "block";
      var popBox = document.getElementById("ChooseCCSL");
      popBox.style.display = "block";
    }
  }

  setSMT(SMTCheck: boolean) {
    this.SMTCheck = SMTCheck;
    if (SMTCheck) {
      var popLayer = document.getElementById("popLayer");
      popLayer.style.display = "block";
      var popBox = document.getElementById("SMTCheck");
      popBox.style.display = "block";
    }
  }

  search(projectName: string) {
    this.projectName = projectName;
    var userName = ''
		if(document.cookie != ''){
			console.log(document.cookie)
			userName = jQuery.parseJSON(document.cookie)['username']
		}
    this.fileService.searchVersion(userName, projectName).subscribe(versions => {
      this.versions = versions;
    });
  }

  openSafeNL() {
    var version = $("input[id='version']:checked").val();
    this.fileService.version = version.toString();
    console.log(this.fileService.version)
    var userName = ''
		if(document.cookie != ''){
			console.log(document.cookie)
			userName = jQuery.parseJSON(document.cookie)['username']
		}
    if (this.projectName != undefined && version != undefined) {
      this.fileService.getSafeNL(userName, this.projectName, this.fileService.version).subscribe(safeNLList => {
        let safenl : string = "";
        for(let str of safeNLList){
          safenl = safenl + str + "\n";
        }
        this.safenlService.safeNL = safenl;
        if(this.isNew){
          this.textService.register(
            this.projectName,
            "undefined",
            safenl
          );
        }
        else{
          this.textService.editor.setValue(safenl);
        }
      });;
      document.getElementById("SafeNL-P").style.zIndex = "1";
    }
    this.close("OpenProject");
  }

  close(id: string) {
    ////console.log("close");
    document.getElementById(id).style.display = "none";
    document.getElementById("popLayer").style.display = "none";
  }

  
  pOntologyShow: boolean;
  eOntologyShow: boolean;
  nodes: string[];
  eNodes: string[];
  subnodes: string[];
  subnodes1: string[];
  clicknode = null;
  clicknode1 = null;
  owlAdd: string;
  powlName: string;
  eowlName: string;

  constructor(
    private fileService: FileService,
    private textService: TextService,
    private safenlService: SafenlService,
    private recordTimeService: RecordTimeService
  ) {

    fileService.newProEmmited$.subscribe(res => {
      ////console.log(res);
      if (res == true) {
        let popLayer = document.getElementById("popLayer");
        popLayer.style.display = "block";
        let ele = document.getElementById("projectPopBox");
        ////console.log(ele);
        ele.style.display = "block";
      }
    });

    this.pOntologyShow = false;
    this.eOntologyShow = false;
  }

  //new project
  confirm() {
    let selectedDiv = document.getElementById("projectPopBox");
    let projectName = $("input[id='fileName']").val().toString();
    console.log(projectName);
    this.projectName = projectName;
    var userName = ''
		if(document.cookie != ''){
			console.log(document.cookie)
			userName = jQuery.parseJSON(document.cookie)['username']
		}
    if (projectName == null || projectName == undefined || projectName == '') {
      alert("The project title can't be null");
    } else {
        this.fileService.setProject(userName, projectName).subscribe(res => {
        if(res){
          document.getElementById("SafeNL-P").style.zIndex = "1"; //显示编辑框
          var that = this;
          that.textService.register(
              projectName,
              "undefined",
              null
          );
          this.closePopEdit();     
        }else{
          alert(projectName + " already exist!");
        }
      });
    }
  }

  ChooseCCSL() {
    var way = $("input[id='state']:checked").val();
    // this.fileService.version = way.toString();
    console.log(way);

    if(way == 'no'){
      this.toCCSL('');
    }else if(way == "exclude"){
      let popLayer = document.getElementById("popLayer");
        popLayer.style.display = "block";
        let ele = document.getElementById("addExclude");
        ele.style.display = "block";
    }else{
      document.getElementById("stateFile").click();
    }
    this.close("ChooseCCSL");
  }

  toCCSL(stateFileName: string){
    var userName = ''
		if(document.cookie != ''){
			console.log(document.cookie)
			userName = jQuery.parseJSON(document.cookie)['username']
    }
    console.log(stateFileName)
		this.safenlService.toCCSL(userName, this.projectName, this.fileService.version, stateFileName).subscribe( ccsls => {
      this.safenlService.ccsls = ccsls;
      this.safenlService.getCCSL(ccsls);
      this.safenlService.isCCSL(true);
    });
  }

  // toCCSL_Exclude(stateFileName: string){
  //   var safenl = this.textService.getText();
  //   var result: boolean;
  //   var next = confirm('Save change in SafeNL?');
  //   console.log(next);
	// 	if(next){
  //     this.fileService.saveSafeNL(this.projectName, this.fileService.version, safenl).subscribe(res => {
  //       if(res){
  //         alert("save succeed!");
  //       }else{
  //         alert("save failed!");
  //       }
  //       console.log(this.projectName);
  //       this.safenlService.toCCSL(this.projectName, stateFileName).subscribe( ccsls => {
  //         this.safenlService.getCCSL(ccsls);
  //         this.safenlService.isCCSL(true);
  //       });
  //     });			
	// 	}else{
  //     this.safenlService.toCCSL(this.projectName, stateFileName).subscribe( ccsls => {
  //       this.safenlService.getCCSL(ccsls);
  //       this.safenlService.isCCSL(true);
  //     });
  //   }
    
  // }

  //setSMTInformation
  setSMTInfo() {
    let TimeOut = $("input[id='TimeOut']").val();
    let Bound = $("input[id='Bound']").val();
    let Period = $("input[id='Period']").eq(0).is(":checked");
    let PeriodValue = $("input[id='PeriodValue']").val();
    let Deadlock = $("input[id='Deadlock']").eq(0).is(":checked");
    console.log(TimeOut);
    console.log(Bound);
    console.log(Period);
    console.log(PeriodValue);
    console.log(Deadlock);
    this.close("SMTCheck");
    var userName = ''
		if(document.cookie != ''){
			console.log(document.cookie)
			userName = jQuery.parseJSON(document.cookie)['username']
    }
    console.time("smt-time"); 
    this.safenlService.SMTCheck(userName,this.projectName, this.fileService.version, Number(TimeOut), Number(Bound), Period, Number(PeriodValue), Deadlock).subscribe( results => {
      this.safenlService.setSMTRes(results);
      console.log(results);
      console.timeEnd("smt-time");
    });
  }

  closeBox() {
    this.closePopEdit();
  }
  closePopEdit() {
    //let selectedType = this.dg_service.getElementType(this.dg_service.selectedElement);
    document.getElementById("projectPopBox").style.display = "none";
    document.getElementById("popLayer").style.display = "none";
  }

  uploader: FileUploader = new FileUploader({
    method: "POST",
    itemAlias: "file",
    autoUpload: false
  });
  // project;

  selectedFileOnChanged(event: any) {
      let stateFileName = this.uploader.queue[0].file.name;
      let fileAddress = stateFileName.substring(
        0,
        stateFileName.length - 4
      );
      console.log(stateFileName)
      console.log(fileAddress);
      var userName = ''
      if(document.cookie != ''){
        console.log(document.cookie)
        userName = jQuery.parseJSON(document.cookie)['username']
      }
      var that = this;
      this.interval = setInterval(function() {
        clearInterval(that.interval);
        that.fileService.uploadState(that.uploader, userName, this.projectName, this.fileService.version);
      }, 100);
      this.toCCSL(stateFileName);
  }

  AddExclude(){
    //get message from popBox
    let selectedDiv = document.getElementById("addExclude");
    //name
    let state1 = $("input[id='state1']").val();

    let state2 = $("input[id='state2']").val();  
    this.excludeList.push(state1 + " exclude " + state2);
    // console.log()
    }
    
    selectExclude(sObject, exclude) {
      $(sObject).attr("style", "BACKGROUND-COLOR: #e6f0fc");
      this.exclude = exclude;
    }

    DeleteExclude(){
      for( var i = 0; i < this.excludeList.length; i ++ ){
        let exclude = this.excludeList[i];
        if(exclude == this.exclude){
          this.excludeList.splice(i, 1);
        }
      }
    }

  setExclude(){
    // this.textService.editor.setValue(safenl);
    const count =this.textService.editor.getModel().getLineCount();
    console.log(count);
    let pos = {
      lineNumber: Number(count),
      column: Number(count)
    }
    var userName = ''
		if(document.cookie != ''){
			console.log(document.cookie)
			userName = jQuery.parseJSON(document.cookie)['username']
		}
    this.textService.editor.setPosition(pos);
    this.textService.editor.revealPositionInCenter(pos, 1 /* Immediate */);
    for(let tmp of this.excludeList){
      this.insertContent(tmp);
    }
    this.safenlService.safeNL = this.textService.getText();
    this.fileService.saveSafeNL(userName, this.projectName, this.fileService.version, this.safenlService.safeNL).subscribe(res => {
      if(res){
        this.toCCSL("");
      }else{
        alert("Failed to add exclude!");
        return
      }
    });
    this.close("addExclude");
   }

   insertContent (text: string) {
    var position = this.textService.editor.getPosition();
    this.textService.editor.executeEdits('', [{
      range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column), 
      // range: {
      //     startLineNumber: position.lineNumber,
      //     startColumn: position.column,
      //     endLineNumber: position.lineNumber,
      //     endColumn: position.column
      // },
      text: "\n" + text
  }]);
  }

  importFile(){
    document.getElementById("safenlFile").click();
  }

  selectedSafenlFileOnChanged(event: any) {
    var userName = ''
		if(document.cookie != ''){
			console.log(document.cookie)
			userName = jQuery.parseJSON(document.cookie)['username']
		}
    let safenlFileName = this.uploader.queue[0].file.name;
    this.projectName = safenlFileName.substring(
      0,
      safenlFileName.length - 7
    );
    console.log(this.projectName);
    var that = this;
    this.interval = setInterval(function() {
      clearInterval(that.interval);
      that.fileService.uploadFile(that.uploader, userName, that.projectName);
    }, 100);

    this.fileService.getSafeNL(userName, this.projectName, "").subscribe(safeNLList => {
      let safenl : string = "";
      for(let str of safeNLList){
        safenl = safenl + str + "\n";
      }
      if(this.isNew){
        this.textService.register(
          this.projectName,
          "undefined",
          safenl
        );
      }
      else{
        this.textService.editor.setValue(safenl);
      }
    });;
    document.getElementById("SafeNL-P").style.zIndex = "1";
  }
}
